package com.yejing.redisdemoTest;

import org.junit.Test;
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import sun.reflect.generics.reflectiveObjects.LazyReflectiveObjectGenerator;

public class Lock {


    public static Jedis jedis = null;

    static {
        if(null == jedis){
            DefaultJedisClientConfig config =
                    DefaultJedisClientConfig.builder() //
                            .password("123456") //
                            .build(); //
            HostAndPort hostPort = new HostAndPort("43.136.67.62", 6379);
            jedis = new Jedis(hostPort, config);
        }
    }


    private String key;
    private Long seconds;

    public Lock(String key, Long seconds) {
        this.key = key;
        this.seconds = seconds;
    }

    public Lock() {
    }

    public boolean lock(){
        long setnx = jedis.setnx(key, key + System.currentTimeMillis());
        long pexpire = jedis.pexpire(key, seconds * 1000);
        if(setnx == 1){
            return true;
        }
        return false;
    }

    public void release(){
        if(jedis.exists(key)){
            jedis.del(key);
        }
    }



}
